import Cookies from 'js-cookie'
import CryptoJS from 'crypto-js'

const TOKEN_KEY = 'enterprise_admin_token'
const SECRET_KEY = 'enterprise_admin_secret'

export const getToken = (): string | undefined => {
    return Cookies.get(TOKEN_KEY)
}

export const setToken = (token: string): void => {
    const encryptedToken = CryptoJS.AES.encrypt(token, SECRET_KEY).toString()
    Cookies.set(TOKEN_KEY, encryptedToken, { expires: 7 })
}

export const removeToken = (): void => {
    Cookies.remove(TOKEN_KEY)
}

export const decryptToken = (encryptedToken: string): string => {
    try {
        const bytes = CryptoJS.AES.decrypt(encryptedToken, SECRET_KEY)
        return bytes.toString(CryptoJS.enc.Utf8)
    } catch {
        return ''
    }
}

export const isTokenExpired = (token: string): boolean => {
    try {
        const payload = JSON.parse(atob(token.split('.')[1]))
        const currentTime = Date.now() / 1000
        return payload.exp < currentTime
    } catch {
        return true
    }
} 